import React, { useState } from 'react';
import styled from 'styled-components';
import { motion } from 'framer-motion';
import { useAuth } from '../contexts/AuthContext';
import { logInfo, logError } from '../logger';
import api from '../services/api';

// 样式组件
const PageContainer = styled.div`
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
  min-height: calc(100vh - 120px);
`;

const Header = styled.header`
  text-align: center;
  margin-bottom: 2rem;
`;

const Title = styled.h1`
  font-size: 2.5rem;
  color: ${props => props.theme.colors.primary};
  margin-bottom: 0.5rem;
`;

const Subtitle = styled.p`
  font-size: 1.2rem;
  color: ${props => props.theme.colors.textSecondary};
  margin-bottom: 2rem;
`;

const FormContainer = styled.div`
  background: ${props => props.theme.colors.cardBackground};
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
`;

const Form = styled.form`
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
`;

const InputGroup = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
`;

const Label = styled.label`
  font-weight: 600;
  color: ${props => props.theme.colors.textPrimary};
`;

const Input = styled.input`
  padding: 0.75rem 1rem;
  border: 2px solid ${props => props.theme.colors.border};
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s ease;

  &:focus {
    outline: none;
    border-color: ${props => props.theme.colors.primary};
  }
`;

const Button = styled.button`
  padding: 0.75rem 1.5rem;
  background: ${props => props.theme.colors.primary};
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.3s ease;
  align-self: flex-start;

  &:hover {
    background: ${props => props.theme.colors.primaryHover};
  }

  &:disabled {
    background: ${props => props.theme.colors.disabled};
    cursor: not-allowed;
  }
`;

const ResultContainer = styled.div`
  background: ${props => props.theme.colors.cardBackground};
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
`;

const SectionTitle = styled.h2`
  color: ${props => props.theme.colors.primary};
  margin-bottom: 1rem;
  font-size: 1.5rem;
`;

const TagsContainer = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-bottom: 1.5rem;
`;

const Tag = styled.span`
  background: ${props => props.theme.colors.primary};
  color: white;
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-size: 0.875rem;
`;

const TraitsList = styled.ul`
  list-style-type: none;
  padding: 0;
`;

const TraitItem = styled.li`
  padding: 0.5rem 0;
  border-bottom: 1px solid ${props => props.theme.colors.border};
  
  &:last-child {
    border-bottom: none;
  }
  
  &::before {
    content: "✓";
    color: ${props => props.theme.colors.primary};
    font-weight: bold;
    margin-right: 0.5rem;
  }
`;

const SuggestionsList = styled.ul`
  list-style-type: none;
  padding: 0;
`;

const SuggestionItem = styled.li`
  padding: 0.5rem 0;
  border-bottom: 1px solid ${props => props.theme.colors.border};
  
  &:last-child {
    border-bottom: none;
  }
  
  &::before {
    content: "💡";
    margin-right: 0.5rem;
  }
`;

const InterpretationText = styled.p`
  line-height: 1.6;
  color: ${props => props.theme.colors.textPrimary};
`;

const ActionButtons = styled.div`
  display: flex;
  gap: 1rem;
  margin-top: 1.5rem;
`;

const SecondaryButton = styled.button`
  padding: 0.75rem 1.5rem;
  background: ${props => props.theme.colors.secondary};
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.3s ease;
  align-self: flex-start;

  &:hover {
    background: ${props => props.theme.colors.secondaryHover};
  }

  &:disabled {
    background: ${props => props.theme.colors.disabled};
    cursor: not-allowed;
  }
`;

const ErrorMessage = styled.div`
  background: #fee;
  color: #c33;
  padding: 1rem;
  border-radius: 8px;
  margin-bottom: 1rem;
`;

const LoadingSpinner = styled.div`
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: ${props => props.theme.colors.primary};
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin: 1rem auto;

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }
`;

/**
 * 姓名测算页面组件
 */
const NameAnalysis = () => {
  // 状态管理
  const [name, setName] = useState('');
  const [analysisResult, setAnalysisResult] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const { user } = useAuth();

  /**
   * 处理表单提交
   * @param {Event} e - 表单提交事件
   */
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // 重置状态
    setError(null);
    setAnalysisResult(null);
    
    // 验证输入
    if (!name.trim()) {
      setError('请输入姓名');
      return;
    }
    
    // 检查姓名长度
    if (name.trim().length > 10) {
      setError('姓名长度不能超过10个字符');
      return;
    }
    
    try {
      setLoading(true);
      logInfo('开始姓名测算', { name: name.trim() });
      
      // 调用API进行姓名测算
      const response = await api.post('/api/name-analysis/analyze', {
        name: name.trim()
      });
      
      // 设置结果 - 从response.data.data中提取分析结果
      setAnalysisResult(response.data.data);
      logInfo('姓名测算完成', { name: name.trim() });
    } catch (err) {
      logError('姓名测算失败', { 
        error: err.message, 
        name: name.trim() 
      });
      
      setError('测算失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 保存测算结果
   */
  const handleSaveResult = async () => {
    if (!user) {
      setError('请先登录以保存结果');
      return;
    }
    
    if (!analysisResult) {
      return;
    }
    
    try {
      setLoading(true);
      
      // 调用API保存结果
      await api.post('/api/name-analysis/save', {
        name: analysisResult.name,
        analysis: analysisResult
      });
      
      alert('结果已保存到个人档案');
      logInfo('姓名测算结果已保存', { name: analysisResult.name, userId: user.id });
    } catch (err) {
      logError('保存姓名测算结果失败', { 
        error: err.message, 
        name: analysisResult.name,
        userId: user?.id
      });
      
      setError('保存失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageContainer>
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <Header>
          <Title>姓名测算</Title>
          <Subtitle>探索您姓名中的独特能量与美好寓意</Subtitle>
        </Header>
        
        <FormContainer>
          <Form onSubmit={handleSubmit}>
            <InputGroup>
              <Label htmlFor="name">请输入您的姓名</Label>
              <Input
                id="name"
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="请输入您的姓名"
                maxLength={10}
              />
            </InputGroup>
            
            <Button type="submit" disabled={loading}>
              {loading ? '测算中...' : '开始测算'}
            </Button>
          </Form>
          
          {error && <ErrorMessage>{error}</ErrorMessage>}
          
          {loading && <LoadingSpinner />}
        </FormContainer>
        
        {analysisResult && (
          <ResultContainer>
            <SectionTitle>测算结果</SectionTitle>
            
            <TagsContainer>
              {analysisResult.positiveTags.map((tag, index) => (
                <Tag key={index}>{tag}</Tag>
              ))}
            </TagsContainer>
            
            <SectionTitle>积极特质</SectionTitle>
            <TraitsList>
              {analysisResult.positiveTraits.map((trait, index) => (
                <TraitItem key={index}>{trait}</TraitItem>
              ))}
            </TraitsList>
            
            <SectionTitle>成长建议</SectionTitle>
            <SuggestionsList>
              {analysisResult.growthSuggestions.map((suggestion, index) => (
                <SuggestionItem key={index}>{suggestion}</SuggestionItem>
              ))}
            </SuggestionsList>
            
            <SectionTitle>姓名解读</SectionTitle>
            <InterpretationText>{analysisResult.interpretation}</InterpretationText>
            
            <ActionButtons>
              <Button onClick={handleSaveResult} disabled={loading}>
                {loading ? '保存中...' : '保存结果'}
              </Button>
              <SecondaryButton onClick={() => window.print()}>
                打印结果
              </SecondaryButton>
            </ActionButtons>
          </ResultContainer>
        )}
      </motion.div>
    </PageContainer>
  );
};

export default NameAnalysis;